<?php
namespace app\controllers\api\comment;

use fate\http\Request;
use app\models\CommentCenter;
use app\models\User;
use app\libs\LibUser;

class RepliesController extends \fate\web\PureController {

    public function run() {
        $req = Request::getInstance();

        $pid = $req->getQueryString('pid');
        $lastId = $req->getQueryString('last_id');

        if(!is_numeric($pid)) {
            $this->ajaxReturn(null, 300002);
            exit;
        }
        if(!is_numeric($lastId)) {
            $this->ajaxReturn(null, 300002);
            exit;
        }

        $center = new CommentCenter();
        $pageSize = 5;

        $where = 'status=1 and parent_id='. $pid .' and id > ' . $lastId;
        $total = $center->count($where);
        $data = $center->getListByCondition('id,parent_id,uid,post_time,content', $where, $pageSize);

        if(!$data || 0 === count($data)) {
            $this->ajaxReturn([
                'data' => null,
                'total_replies' => $total,
                'has_more_replies' => false
            ]);
            exit;
        }

        // 有数据
        $userModel = new User();
        $uidsMap = [];
        $userInfoCache = [];
        for($i=0, $len=count($data); $i<$len; $i++) {
            $uidsMap[ 'u' . $data[$i]['uid'] ] = $data[$i]['uid'];
        }
        $userInfo = $userModel->getListByCondition(
            'id, user_name, avatar',
            'id in(' . implode(',', array_values($uidsMap)) . ')'
        );
        for($i=0, $len=count($userInfo); $i<$len; $i++) {
            $userInfoCache[ 'u' . $userInfo[$i]['id'] ] = $userInfo[$i];
        }

        for($i=0, $len=count($data); $i<$len; $i++) {
            $userInfo = $userInfoCache[ 'u' . $data[$i]['uid'] ];

            $data[$i]['avatar'] = $userInfo['avatar'];
            $data[$i]['user_name'] = $userInfo['user_name'];
            $data[$i]['str_uid'] = LibUser::encodeId($data[$i]['uid']);
        }

        $this->ajaxReturn([
            'data' => $data,
            'total_replies' => $total,
            'has_more_replies' => count($data) >= $pageSize
        ]);
    }

}
